package com.rulin.asp.sso.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rulin.asp.sso.entity.User;
import com.rulin.asp.sso.service.AuthService;
import com.rulin.asp.sso.service.UserService;

@Controller
@RequestMapping("/account")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private AuthService menuService;
	
	@RequestMapping("/showAccount")
	public String toShowAccount(HttpServletRequest request, Model model) {
		String user = request.getParameter("user");
		String psd = request.getParameter("psd");
		if (user == null || user == "") {
			model.addAttribute("msg", "账号为空");
			return "login";
		}
		User account = userService.getByUserAccount(user);
		if(account == null){
			model.addAttribute("msg", "该账号不存在");
			return "login";
		}
		if (!account.getPassword().equals(psd)) {
			model.addAttribute("msg", "密码错误");
			return "login";
		}
		String sessionId = request.getSession().getId();
		request.getSession().setAttribute("userName", account.getUserName());
		request.getSession().setAttribute("userId", account.getId());
		request.getSession().setAttribute("userAccount", account.getAccount());
		model.addAttribute("acc", account);
		model.addAttribute("menu", menuService.getMenusByUser(user));
		
		account.setSessionId(sessionId);
		userService.saveUserSessionId(account);
		
		return "default";
	}
	
	@RequestMapping("/toLogin")
	public String toLogin() {
		return "login";
	}
	
	/**
	 * 获取所有教师列表
	 * @return
	 */
	@RequestMapping(value = "/getAllTeachers.json", method = RequestMethod.GET)
	@ResponseBody
	public List<User> getAllTeachers() {
		return userService.getAllTeachers();
	}
	
	/**
	 * 获取所有用户列表
	 * @return
	 */
	@RequestMapping(value = "/getAllUsers.json", method = RequestMethod.GET)
	@ResponseBody
	public List<User> getAllUsers() {
		return userService.getAllUsers();
	}
	
	
	@RequestMapping("/register")
	public String register(HttpServletRequest request, Model model) {
//		String username = request.getParameter("username");
//		String password = request.getParameter("password");
//		String rpsw = request.getParameter("rpsw");
		return "login";
	}
}
